package com.njy.aop.annotation;

import cn.hutool.json.JSONUtil;
import com.njy.pojo.LogInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;


import java.lang.reflect.Method;
import java.time.Duration;
import java.time.LocalDateTime;

@Component
@Aspect
public class LogAspect {

  //  @Around(value = "execution(* com.njy.aop.service..*.*(..))")
    @Around("@annotation(com.njy.aop.annotation.SysLog)")
    public Object around(ProceedingJoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        LogInfo logInfo = new LogInfo();
        Object res = null;
        try {
            LocalDateTime creationDate = LocalDateTime.now();
            res = joinPoint.proceed();
            LocalDateTime finishDate = LocalDateTime.now();
            logInfo.setCreationDate(creationDate);
            logInfo.setFinishDate(finishDate);
            String cost = String.valueOf(Duration.between(creationDate, finishDate).toMillis());
            logInfo.setCost(cost);
            logInfo.setMethod(methodName);
            //注解
            SysLog annotation = method.getAnnotation(SysLog.class);
            logInfo.setDescription(annotation.description());
            logInfo.setOperationType(annotation.operationType().getValue());
            //返回参数
            logInfo.setRespParam(JSONUtil.toJsonStr(res));
            //请求参数
            logInfo.setReqParam(JSONUtil.toJsonStr(joinPoint.getArgs()));
            System.out.println("loginfo----->"+logInfo.toString());
            return  res;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return res;
    }
}
